package v.e.mapper

import org.xml.sax.Attributes
import org.xml.sax.SAXException
import org.xml.sax.helpers.DefaultHandler

class MapperFileSaxHandler(filename: String,parsingSql:Boolean) : DefaultHandler() {

    private var namespace = String()

    private val filename: String = filename

    private val parsingSql: Boolean = parsingSql

    private var currentTag: String? = null

    private var currentSqlId: String?=null

    private var currentSql:StringBuilder?=null

    @Throws(SAXException::class)
    override fun startElement(uri: String?, localName: String?, qName: String?, attributes: Attributes?) {
        super.startElement(uri, localName, qName, attributes)
        if(qName.equals("mapper")){
            namespace=attributes!!.getValue("namespace")
        }
        if(parsingSql && qName.equals("sql")){
            println("filename=${this.filename}")
            println("namespace=${this.namespace}")
            currentSqlId = attributes!!.getValue("id")
            println("currentSQlId=${this.currentSqlId}")
        }

        currentTag = qName
        //println(currentTag)
    }
    @Throws(SAXException::class)
    override fun characters(ch: CharArray?, start: Int, length: Int) {
        super.characters(ch, start, length)
        if(parsingSql && "sql".equals(currentTag)){
            currentSql?.append(String(ch!!,start,length))
//            val sql= String(ch!!,start,length)
        }
    }

    @Throws(SAXException::class)
    override fun endElement(uri: String?, localName: String?, qName: String?) {
        super.endElement(uri, localName, qName)
        if(parsingSql && "sql".equals(currentTag)){
            println(currentSqlId)
            println("----\r\n$currentSql\r\n----")
        }
        currentTag = null
        currentSqlId = null
        currentSql=null
    }

    fun getNamespace(): String {
        return namespace
    }

    fun getFilename() :String{
        return filename
    }
}